package cc.mrbird.febs.common.datasource.starter.organization;

import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.UtilityClass;

/**
 * 租户
 *
 * @author luowei Creation time 2020/10/21 9:52
 */
@UtilityClass
public class OrganizationContextHolder {

    private final ThreadLocal<OrganizationConfig> THREAD_LOCAL_TENANT = new TransmittableThreadLocal<>();

    /**
     * TTL 设置租户ID<br/>
     * <b>谨慎使用此方法,避免嵌套调用。尽量使用 {@code OrganizationBroker} </b>
     *
     * @param organizationId
     * @see OrganizationBroker
     */
    public void setOrganizationConfig(String organizationId, Boolean flag) {
        OrganizationConfig organizationConfig = OrganizationConfig.builder().organizationId(organizationId).organizationFlag(flag).build();
        THREAD_LOCAL_TENANT.set(organizationConfig);
    }

    /**
     * 获取TTL中的租户ID
     *
     * @return
     */
    public String getOrganizationId() {
        return getOrganizationConfig().getOrganizationId();
    }

    /**
     * 获取TTL中的租户Flag
     *
     * @return
     */
    public Boolean getOrganizationFlag() {
        return getOrganizationConfig().getOrganizationFlag();
    }

    /**
     * 获取TTL中的租户ID
     *
     * @return
     */
    public OrganizationConfig getOrganizationConfig() {
        OrganizationConfig organizationConfig = THREAD_LOCAL_TENANT.get();
        if (organizationConfig == null) {
            organizationConfig = OrganizationConfig.builder().organizationId(null).organizationFlag(true).build();
        }
        return organizationConfig;
    }

    public void clear() {
        THREAD_LOCAL_TENANT.remove();
    }

    @Data
    @Builder
    public static class OrganizationConfig {

        private String organizationId;

        private Boolean organizationFlag;

    }

}
